<template>
	<view class="container">
		<view class="top_bar"
			:style="{paddingTop:navBarTop + 'px',height:navBarHeight + 'px',lineHeight:navBarHeight + 'px',paddingRight:navBarRight + 'px' }">
			我的视频
		</view>
		<view class="video-container">
			<view class="">
				<u-tabs :list="list1" lineWidth="30" lineColor="#f66e14" :activeStyle="{
            color: '#303133',
            fontWeight: 'bold',
            transform: 'scale(1.05)'
        }" :inactiveStyle="{
            color: '#606266',
            transform: 'scale(1)'
        }" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" @click="tabclick"></u-tabs>
			</view>
			<view class="task-content">
				<view class="task-empty" v-if="dataList.length === 0">
					<u-empty mode="history" text="暂无视频创建记录">
					</u-empty>
				</view>
				<view v-else>
					<scroll-view show-scrollbar="false" scroll-y="true" class="scroll-Y scroll_list"
						@scrolltolower="lower" :style="{ height: `calc(100vh - 94px - ${navBarHeight}px - ${navBarTop}px)` }">
						<view class="content-item" v-for="(item,index) in dataList" :key="index"
							@click="videoDetail(item.taskState,item.id)">
							<view class="content-item-icon">
								<u-icon name="hourglass-half-fill" size="28" color="#F97316"
									v-if="item.taskState == 2"></u-icon>
								<u-icon name="clock-fill" size="28" color="#3B82F6" v-if="item.taskState == 1"></u-icon>
								<u-icon name="info-circle-fill" size="28" color="#EF4444"
									v-if="item.taskState == 4"></u-icon>
								<!-- <u-icon name="pause" size="28" color="#6B7280" v-if="item.taskState == 1"></u-icon> -->
								<view class="img_item" style="width: 100%;" v-if="item.taskState == 3">
									<view class="iconfont icon-bofang1">

									</view>
									<u--image mode='aspectFill' :src="item.coverImg" width="100%"
										height="60px"></u--image>
								</view>
							</view>
							<view class="content-item-info">
								<view class="item-info-title">
									<view class="task-title">{{item.title}}</view>
									<view>
										<view v-if="item.taskState == 2" class="task-type prog">生成中</view>
										<view v-if="item.taskState ==1" class="task-type queue">排队中</view>
										<view v-if="item.taskState == 4" class="task-type error">已失败</view>
										<view v-if="item.taskState == 3" class="task-type success">已完成</view>
									</view>
								</view>
								<view class="item-info-progress" v-show="item.taskProcess">
									<u-line-progress :percentage="item.taskProcess==100?99:item.taskProcess" height="14"
										activeColor="#F97316"></u-line-progress>
									<view class="progcess-desc">
										<view>{{item.taskProcess==100?99:item.taskProcess}}%已完成</view>
										<view>预计剩余:{{item.taskProcessTime=='00:00'?'00.01':item.taskProcessTime}}</view>
									</view>
								</view>
								<view v-show="!item.taskProcess">
									<view v-show="item.taskState == 1" class="item-info-font">
										当前队列位置:{{item.queuePosition}}
									</view>
									<view v-show="item.taskState == 4" class="item-info-font">生成失败</view>
									<!-- <view v-show="item.type == 4" class="item-info-font">等待资源分配</view> -->
									<view v-show="item.taskState == 3" class="item-info-font">视频制作完成</view>
								</view>

								<view class="item-info-font">{{item.insertTime}}</view>
							</view>
						</view>

						<view class="" style="height: 10px;">

						</view>
					</scroll-view>

				</view>

			</view>
		</view>
		<layout />
	</view>
</template>

<script>
	import layout from '../../components/layout/layout.vue';
	export default {
		data() {
			return {
				list1: [{
					name: '全部',
					id: null
				}, {
					name: '已完成',
					id: 3,
				}, {
					name: '生成中',
					id: 2,
				}, {
					name: '排队中',
					id: 1,
				}, {
					name: '失败',
					id: 4,
				}],

				dataList: [

				],
				query: {
					pageNum: 1,
					pageSize: 10,
					taskState: null
				},
				timer: null, // taskState=1的定时器
				navBarTop: 0,
				navBarLeft: 0,
				navBarHeight: 0,

			};
		},
		components: {
			layout,
		},
		onLoad(options) {},
		mounted() {
			uni.$emit('update', {
				active: 1
			}) // 触发事件并传递参数	
			this.tasklistfn()
			//获取胶囊位置
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			this.navBarTop = menuButtonInfo.top;
			this.navBarHeight = menuButtonInfo.height;
			this.navBarLeft = menuButtonInfo.left;
		},
		beforeDestroy() {
			this.clearTimers();
		},
		watch: {

		},
		methods: {
			tabclick(e) {
				this.query.pageNum = 1
				this.query.taskState = e.id
				this.dataList = []
				this.tasklistfn()
			},
			timelist() {
				// 检查是否需要请求特定状态的定时器
				const checkAndRequest = (timerKey) => {
					// 检查dataList中是否有对应状态的数据
					const hasStateData = this.checkTaskState1Or2();

					if (!hasStateData) {
						this.clearTimers()
						return;
					}

					// 如果定时器不存在，则创建
					if (!this[timerKey]) {
						this[timerKey] = setInterval(() => {
							// 再次检查是否还有对应状态的数据
							const hasStateData = this.checkTaskState1Or2();
							if (!hasStateData) {
								this.clearTimers()
								return;
							}

							this.makeRequest();
						}, 5000);
					}
				};

				// 初始检查并启动定时器
				checkAndRequest('timer');
			},

			// 发起请求的方法
			makeRequest() {
				this.$request(`/task/listByPage`, 'post', this.query).then(res => {
					if (res && res.data && res.data.data && res.data.data.records && res.data.data.records.length >
						0) {
						console.log(`返回数据:`, res.data.data.records);
						// 更新dataList中的数据
						this.updateDataList(res.data.data.records);
					}
				}).catch(error => {
					console.log(error);
				});
			},

			// 更新dataList的方法
			updateDataList(newRecords) {
				if (!this.dataList || !newRecords) return;

				this.dataList = this.dataList.map(item => {
					// 只对taskState为1或2的项进行更新
					if (item.taskState === 1 || item.taskState === 2) {
						// 在newRecords中查找相同ID的项
						const matchedRecord = newRecords.find(record => record.id === item.id);
						// 如果找到匹配项，则替换；否则保持原样
						return matchedRecord ? {
							...matchedRecord
						} : item;
					} else {
						// taskState不是1或2的项保持不变
						return item;
					}
				});

				console.log('更新后的dataList:', this.dataList);
				const hasStateData = this.checkTaskState1Or2();

				if (!hasStateData) {
					this.clearTimers()
					return;
				}

			},
			// 清理定时器
			clearTimers() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}

			},
			tasklistfn() {
				this.$request(`/task/listByPage`, 'post', this.query).then(res => {
					this.dataList = res.data.data.records ? this.dataList.concat(res.data.data.records) : [];

					// 检查dataList中是否有taskState为1或2的项
					const hasTaskState1Or2 = this.checkTaskState1Or2();

					if (hasTaskState1Or2) {
						console.log('检测到taskState为1或2的项，调用timelist');
						this.timelist();
					} else {
						this.clearTimers()
						console.log('未检测到taskState为1或2的项，不调用timelist');
					}
				}).catch(error => {
					console.error('请求失败:', error);
				});
			},

			// 检查dataList中是否有taskState为1或2的项
			checkTaskState1Or2() {
				if (!this.dataList || this.dataList.length === 0) {
					return false;
				}
				return this.dataList.some(item => item.taskState === 1 || item.taskState === 2);
			},


			lower() {
				this.query.pageNum++
				this.tasklistfn()
			},
			changeCard(num, e) {
				this.query.pageNum = 1
				this.query.taskState = e > 0 ? e : null
				this.dataList = []
				this.tasklistfn()
				this.cardNum = num;
			},
			videoDetail(type, id) {
				// this.clearTimers()
				const that = this
				const obj = {
					type: type,
					id: id
				}
				// 传值 当前卡片的状态
				uni.navigateTo({
					url: '/pages/video/video_detail?type=' + encodeURIComponent(JSON.stringify(obj)),

				})
			}
		}
	};
</script>



<style scoped lang="scss">
	.video-container {
		width: 100%;
		height: auto;
		min-height: 100vh;
		box-sizing: border-box;
		/* padding: 10px 0px 0px; */
		background-color: #f7fbfe !important;
	}

	.top_bar {
	font-size: 30rpx;
		background-color: #f7fbfe !important;
		text-align: center;
	}

	.task-container {
		box-sizing: border-box;
		padding: 10px 10px 0 10px;
		margin-bottom: 60px;
		border-radius: 15px 15px 0 0;
		min-height: calc(100vh - 108px);
	}



	.task-content {
		width: calc(100%);
		height: auto;
	}

	.task-empty {
		width: 100%;
		height: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.content-item {
		display: flex;
		width: 100%;
		height: auto;
		margin-bottom: 10px;
		border-radius: 10px;
		box-sizing: border-box;
		padding: 10px 10px;
		background-color: #fff;
		border: 1px solid #f4f4f4;
		box-shadow: 0 5px 8px -2px rgba(162, 175, 194, 1);

	}

	.content-item-icon {
		width: 60px;
		margin-right: 10px;
		display: flex;
		align-items: center;
		justify-content: center;

	}

	.img_item {
		position: relative;


	}

	.icon-bofang1 {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 1000;
		color: rgba(232, 232, 232, 0.7);
	}

	.content-item-info {
		width: calc(100% - 70px);
		/* flex: 1; */
	}

	.item-info-title {
		width: 100%;
		height: 30px;
	}

	.item-info-title .task-title {
		float: left;
		width: calc(100% - 60px);
		font-size: 28rpx;
		color: #333;
		line-height: 30px;
		font-weight: 600;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.item-info-title .task-type {
		float: left;
		width: 60px;
		height: 24px;
		text-align: center;
		line-height: 24px;
		font-size: 22rpx;

		border-radius: 20px;

	}

	.item-info-progress {
		margin-top: 10px;
	}

	.progcess-desc {
		display: flex;
		justify-content: space-between;
		font-size: 14px;
		color: #64748B;
		margin-top: 5px;
	}

	.item-info-font {
		font-size: 14px;
		color: #64748B;
		margin-top: 5px;
	}

	.scroll_list {

		/* padding-bottom: 10px; */
		width: calc(100% - 20px);
		padding: 0 10px;

		::-webkit-scrollbar {
			width: 0px;
			/* 滚动条的宽度 */
		}
	}

	.prog {
		color: #F97316;
		background-color: #FFEDD5;
	}

	.queue {
		color: #3B82F6;
		background-color: #DBEAFE;
	}

	.error {
		color: #EF4444;
		background-color: #FEE2E2;
	}

	.load {
		color: #6B7280;
		background-color: #E5E7EB;
	}

	.success {
		color: #fff;
		background-color: #67C23A;
	}
</style>